package com.youlu.campus.activity.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.youlu.campus.activity.entity.ActivityLotteryPrize;
import com.youlu.campus.activity.entity.ActivityLotteryPrizeNameVo;
import com.youlu.campus.activity.entity.ActivityLotteryPrizeQueryVo;
import com.youlu.campus.activity.repositories.ActivityLotteryPrizeRepository;
import com.youlu.campus.activity.service.ActivityLotteryPrizeService;
import com.youlu.campus.common.utils.RedisKeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * 活动抽奖奖品
 *
 * @Description: ActivityLotteryPrizeServiceImpl
 * @Date 2025/7/31
 * @module ActivityLotteryPrizeServiceImpl
 * @author: su
 */
@Slf4j
@Service
public class ActivityLotteryPrizeServiceImpl implements ActivityLotteryPrizeService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private ActivityLotteryPrizeRepository activityLotteryPrizeRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public ActivityLotteryPrize save(ActivityLotteryPrize prize) {
        log.info("save param prize:{}", prize);
        if (StringUtils.isBlank(prize.getId())) {
            prize.setCreateTime(LocalDateTime.now());
            prize.setId(null);
        } else {
            prize.setUpdateTime(LocalDateTime.now());
        }
        ActivityLotteryPrize save = activityLotteryPrizeRepository.save(prize);
        deleteTedisCache(save.getId());
        log.info("save result prize:{}", prize);
        return save;
    }

    @Override
    public boolean delete(String prizeId) {
        log.info("save delete prizeId:{}", prizeId);
        Optional<ActivityLotteryPrize> optional = activityLotteryPrizeRepository.findById(prizeId);
        if (!optional.isPresent()) {
            log.error("delete ActivityLotteryPrize is null prizeId:{}", prizeId);
            return false;
        }
        ActivityLotteryPrize activityLotteryPrize = optional.get();
        activityLotteryPrize.setDeleted(true);
        activityLotteryPrizeRepository.save(activityLotteryPrize);
        deleteTedisCache(prizeId);
        log.info("save result prizeId:{}", prizeId);
        return true;
    }


    @Override
    public Page<ActivityLotteryPrize> findByPage(ActivityLotteryPrizeQueryVo paramVo) {
        Query query = new Query();
        query.addCriteria(Criteria.where("deleted").is(false));
        if (StringUtils.isNotBlank(paramVo.getPrizeName())) {
            query.addCriteria(Criteria.where("prizeName").regex(paramVo.getPrizeName()));
        }
        if (Objects.nonNull(paramVo.getPrizeType())) {
            query.addCriteria(Criteria.where("prizeType").is(paramVo.getPrizeType()));
        }
        //统计总条数（分页需要先查总数）
        long total = mongoTemplate.count(query, ActivityLotteryPrize.class);
        //创建分页对象
        Pageable pageRequest = PageRequest.of(paramVo.getPage() - 1, paramVo.getPageSize());
        List<ActivityLotteryPrize> list;
        if (total == 0) {
            list = Arrays.asList();
        } else {
            // 应用分页（设置跳过的条数和查询的条数）
            query.skip(pageRequest.getOffset()).limit(pageRequest.getPageSize());
            list = mongoTemplate.find(query, ActivityLotteryPrize.class);
        }
        return PageableExecutionUtils.getPage(list, pageRequest, () -> total);
    }

    @Override
    public ActivityLotteryPrize findById(String prizeId) {
        String key = RedisKeyUtil.getActivityLotteryPrize(prizeId);
        String value = redisTemplate.opsForValue().get(key);
        if (StringUtils.isNotBlank(value)) {
            return JSONObject.parseObject(value, ActivityLotteryPrize.class);
        }
        Optional<ActivityLotteryPrize> optional = activityLotteryPrizeRepository.findById(prizeId);
        if (!optional.isPresent()) {
            return null;
        }
        ActivityLotteryPrize activityLotteryPrize = optional.get();
        redisTemplate.opsForValue().set(key, JSONObject.toJSONString(activityLotteryPrize), 1, TimeUnit.DAYS);
        return activityLotteryPrize;
    }

    @Override
    public List<ActivityLotteryPrizeNameVo> findNameByIds(String[] idArr) {
        List<ActivityLotteryPrize> list = activityLotteryPrizeRepository.findByIdIn(Arrays.asList(idArr));
        if (list.isEmpty()) {
            return Arrays.asList();
        }

        List<ActivityLotteryPrizeNameVo> result = new ArrayList<>();
        for (ActivityLotteryPrize activityLotteryPrize : list) {
            ActivityLotteryPrizeNameVo activityLotteryPrizeNameVo = new ActivityLotteryPrizeNameVo();
            activityLotteryPrizeNameVo.setId(activityLotteryPrize.getId());
            activityLotteryPrizeNameVo.setPrizeName(activityLotteryPrize.getPrizeName());
            result.add(activityLotteryPrizeNameVo);
        }
        return result;
    }

    private void deleteTedisCache(String prizeId) {
        String key = RedisKeyUtil.getActivityLotteryPrize(prizeId);
        redisTemplate.delete(key);
    }
}
